var CartManager = {
    init : function () {
        this.initCart();
    } , 
    id : null,
    cart : false ,
    reload : function () {
        CartManager.waitingLayer(1);
        var params = CartManager._getParams();
//        CartManager.showWaitingLayer(true);
        $.getJSON('/flow/cart/list/', params, CartManager.render);
    } , 
    
    render : function (json) {
        var data = json.data;
        if (json.code !== 0) {
            switch (json.code) {
                case -100 :
                    location.reload();
                    break;
                default :
                    alert(json.message);
            }
            return;
        }
        if (typeof (data.html) != 'undefined') {
            $('div[data-role="cart"]').html(data.html);
        }
        if (typeof (data.params)) {
            CartManager.cart = data.params; //保存商品信息
            CartManager.id = data.id;
        }
        CartManager.initCart();
        CartManager.waitingLayer(0);
    } , 
    
    initCart : function () {
        CartManager.initCheckbox();
        CartManager.initProduct();
        $('input[data-role="actSelect"]').click(function(){
            CartManager.reload();
        });
        if ($('input:checked[data-role="product"]').length == $('input:checkbox[data-role="product"]').length) {
            $('input:checkbox[data-role="all"]').attr('checked',true);
        } else {
            $('input:checkbox[data-role="all"]').attr('checked',false);
        }
         //购物车吸顶
        CartManager.ceilingAlamp();
    } ,
    
    initProduct : function () {
       $('div[data-role="product"]').each(function () {
           var product = $(this).attr('data-attr');
           var amt = $(this).find("input[name='amt']");
           function afterChange () {
               if (amt.val()>=6) {
                   amt.val(6);
                   amt.next().addClass('disabled');
               } else {
                   amt.next().removeClass('disabled');
               }
               if (amt.val()<=1) {
                   amt.val(1);
                   amt.prev().addClass('disabled');
               } else {
                   amt.prev().removeClass('disabled');
               }
           }
           amt.next().click(function(){ //增加数量
               if (amt.val()<6) {
                   amt.val(parseInt(amt.val())+1);
                   CartManager.updateCart(product , 'update', {"amount": amt.val()});
               }
               afterChange();
           });
           amt.prev().click(function(){//减少数量
               if (amt.val()>1) {
                   amt.val(parseInt(amt.val())-1);
                   CartManager.updateCart(product , 'update', {"amount": amt.val()});
               }
               afterChange();
           });
           $(this).find('i[data-role="del"]').click(function(){
               CartManager.updateCart(product , 'update', {"amount": 0});
           });
           afterChange();
       });
       $('em[data-role="removeExpire"]').click(function(){
           var product = $(this).attr('data-attr');           
           $(this).parents('li').remove();
           CartManager.updateCart(product , 'update', {"amount": 0});
       });
    } ,
    
    initCheckbox : function () {
        //initcheckbox
        $('input:checkbox[data-role="product"]').change(function () {
            if ($(this).attr("checked") == false) {
                $('input:checkbox[data-role="all"]').attr("checked" , false);
            }
            CartManager.reload();
        });
        $('input:checkbox[data-role="all"]').change(function(){
            var checked = $(this).attr('checked') == 'checked' ? 'checked' : false;
            $('input:checkbox[data-role="product"],input:checkbox[data-role="all"]').attr('checked',checked);
            CartManager.reload();
        });
        $('div[data-role="remove_all"]').click(function(){
            var products = [];
            var i = $('input:checkbox[data-role="product"]').each(function(){
                var parent = $(this).parents('div[data-role="product"]');
                console.log(parent);
                var p = {
                    "product_id" : parent.dataAttr('product_id') , 
                    "goods_id" : parent.dataAttr('goods_id'),
                    "amt" : parent.dataAttr('amt'),
                    "number" : 0 
                };
                if (p) {
                    products.push(p);
                }
            });
            CartManager.updateCart(products,'batchDelete');
        });
        $('div[data-role="removeExpires"]').click(function(){
            var products = [];
            var i = $('em[data-role="removeExpire"]').each(function(){
                var p = {
                    "product_id" : $(this).dataAttr('product_id') , 
                    "goods_id" : $(this).dataAttr('goods_id'),
                    "amt" : $(this).dataAttr('amt'),
                    "number" : 0 
                };
                if (p) {
                    products.push(p);
                }
            });
            CartManager.updateCart(products,'batchDelete');
        });
        $('input:checkbox[data-role="act"]').change(function () {
            var obj = this;
            $(this).parents('ul').find('input:checkbox[data-role="act"]').each(function(){
                if (this!=obj) {
                    $(this).attr('checked' , false);
                }
            }) ;
        });
    } , 
    
    /**
     * 更新购物车 
     * @param string product
     * @param string type [update|delete|change]
     * @param object data 
     * @returns boolean
     */
    updateCart: function(product, type, data) {
        if (typeof (product) == 'string') {
            product = JSON.parse(product);
        }
        if (typeof (type) == 'undefined') {
            return false;
        }
        switch (type) {
            case "update" :
                if (typeof product['number'] == 'undefined' && data) {
                    product['number'] = data.amount;
                }
                $.getJSON('/flow/cart/UpProduct', {"goods": JSON.stringify([product])}, function() {
                    CartManager.reload();
                });
                break;
            case "delete" :
                product.number = 0;
                $.getJSON('/flow/cart/UpProduct', {"goods": JSON.stringify([product])}, function() {
                    CartManager.reload();
                });
                break;
            case 'batchDelete' :
                $.getJSON('/flow/cart/UpProduct', {"goods": JSON.stringify(product)}, function() {
                    CartManager.reload();
                });
                break;
            case "change" :
                break;
        }
    } , 
    showSubmit : function () {
        $(".sc_layer,.balance_layer").show();
    } ,
    
    /*订单提交*/
    submit: function(orderNo) {
        var params = {"cart": JSON.stringify(CartManager.cart),"id":CartManager.id};
        if (typeof(orderNo) === 'undefined') {
        } else {
            params.orderNo = orderNo;
        }
        if (this.cart.order.amt <= 0) {
            alert("您没有选中任何商品 !");
            return;
        }
        this._submit('/flow/createorder/show/', params , "post");
    },
    /**
     * 创建表单提交
     * @param string url
     * @param object params
     * @returns null
     */
    _submit: function(url, params, method) {
        if (typeof (params) !== "object")
            return;
        var form_name = "cart_form_" + Math.round(Math.random() * 100000);
        var btn_name = form_name + '_btn';
        var form = '<form id="' + form_name + '" action="' + url + '" method="' + ((typeof (method) == "get") ? "get" : "post") + '">';
        for (var i in params) {
            form += "<input type='hidden' name='" + i + "' value='" + params[i] + "'/>";
        }
        form += "<input type=submit id='" + btn_name + "'/></form>";
        $('body').append(form);//赋值表单到
        $('#' + btn_name).click(); //兼容ie6
        if ($.browser.msie && $.browser.version <= 6.0) {
            setTimeout(function() {
                $('#' + btn_name).click();
            }, 1000);
        }
    },
    _getParams : function () {
        var params = {
            'selectedProductIds': [],
            'selectedActIds': []
        };
        $('input:checked[data-role="act"]').each(function() {
            params.selectedActIds.push(JSON.parse($(this).val()));
        });
        $('input:checked[data-role＝"product"]').each(function(){
            var product = $(this).parents('div[data-role="product"]').dataAttr('product_id');
            if (product) {
                params.selectedProductIds.push(product);
            }
        });
        return params;
    } , 
    waitingLayer : function (isShow) {
        if (isShow) 
        $('[data-role="waitingLayer"]').show();
        else
        $('[data-role="waitingLayer"]').hide();
    } ,
    ceilingAlamp: function () {
        // c_balance_bt fixed_bt
        var $con = $(".c_balance");
        var count_bar_pos = $con.position().top + $con.outerHeight() + 51;
        if ($(document).scrollTop() + $(window).height() < count_bar_pos) {
            $(".c_balance_bt").addClass("fixed_bt");
        }

        $(window).scroll(function () {
            if ($(document).scrollTop() + $(window).height() < ($con.position().top + $con.outerHeight() + 21)){
                $(".c_balance_bt").addClass("fixed_bt")
            }
            else {
                $(".c_balance_bt").removeClass("fixed_bt")
            }
        });
    }
}

CartManager.init();